package me.leiusual.sharing.ui.mine

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_mine_message.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.mine.adapter.MineMessageAdapter
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/16
 */
class MineMessageFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: MineMessageViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_mine_message, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    recycler_view.adapter = MineMessageAdapter {
      Timber.v("已读")

      viewModel.userMessageView(it.id)
    }

    observeData()
    viewModel.userMessageQuery()
  }

  private fun observeData() {
    viewModel.loadInitial.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("loadInitial = %s", it)
      when (it) {
        is Data.Loading -> {
          state_constraint_layout.showProgress()
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()
        }
      }
    })

    viewModel.userMessageQuery.observe(viewLifecycleOwner, Observer {
      Timber.v("userMessageQuery = %s", it)

      if (it.isEmpty()) {
        state_constraint_layout.showEmpty()
      } else {
        state_constraint_layout.showContent()

        val adapter = recycler_view.adapter as MineMessageAdapter
        adapter.submitList(it)
      }
    })
  }
}